package online.misscl.lsy.util;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import online.misscl.lsy.service.VaccineUserService;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 自动补充插入或更新时的值
 * @Author: code mover
 * @Date: 2023/03/17/11:29
 */
@Component
public class MpMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    @Lazy
    private VaccineUserService vaccineUserService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public void insertFill(MetaObject metaObject) {
        if(metaObject.hasSetter("createTime")){
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
        if(metaObject.hasSetter("createBy")){
            if(JwtUtils.getUserId(httpServletRequest) != 0){
                this.setFieldValByName("createBy", vaccineUserService.getById(JwtUtils.getUserId(httpServletRequest)).getName(), metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(metaObject.hasSetter("updateTime")){
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
        if(metaObject.hasSetter("updateBy")){
            this.setFieldValByName("updateBy", vaccineUserService.getById(JwtUtils.getUserId(httpServletRequest)).getName(), metaObject);
        }
    }

}